# -*- coding:utf-8 -*-
#author: IAMLIUBO
#B站评论抽奖程序

import requests
import re
import os
import sys
import json
import random

info_list = []

def bvid2aid(bvid):
    aid_url = "http://api.bilibili.com/x/web-interface/view?bvid=" + str(bvid)
    aid_r = requests.get(aid_url)
    aid_text = aid_r.text
    aid_json_text = json.loads(aid_text)
    aid = aid_json_text["data"]["aid"]
    # print("\nget aid:" + str(aid) + "\n")
    return aid

def getCommentListByAVid(aid):
    global flag
    url = "http://api.bilibili.com/x/reply?type=1&oid=" + str(aid) + "&pn=0&nohot=1&sort=0"
    r = requests.get(url)
    numtext = r.text
    json_text = json.loads(numtext)
    commentsNum = json_text["data"]["page"]["count"]
    page = commentsNum // 20 + 1
    for n in range(0,page):
        url = "https://api.bilibili.com/x/v2/reply?jsonp=jsonp&pn=" + str(n+1) + "&type=1&oid=" + str(aid) + "&sort=2&nohot=1"
        req = requests.get(url)
        text = req.text
        json_text_list = json.loads(text)
        for i in json_text_list["data"]["replies"]:
            if (i["member"]["uname"]) not in info_list:
                info_list.append(i["member"]["uname"])

    # print(info_list)
    

def main(bvid):

    aid = bvid2aid(bvid)

    getCommentListByAVid(aid)

    print("\n--- 待抽奖人列表 ---\n") 

    for i in range(0, len(info_list)):
        print(str(i) + " " + str(info_list[i]))


    print("\n--- Congratulations!!! --- \n")

    alist = random.sample(range(0, len(info_list)), 1)

    print("中奖者: " + str(info_list[alist[0]]) + "\n")


    
if __name__ == "__main__":

    if len(sys.argv) < 2:
        print("Usage: \n" + "     python3 " + sys.argv[0] + " <bvid>")
    else:
        main(sys.argv[1])
    
    

    
